package com.future.common.interceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.JsonKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ActionPerformanceLoggingInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		Map<String, Object> logMap = new HashMap<String, Object>();
		String className = inv.getTarget().getClass().getName();
		String methodName = inv.getMethodName();
		Object[] args = inv.getArgs();
		Date startTime = new Date();
		logMap.put("className", className);
		logMap.put("methodName", methodName);
		logMap.put("startTime", startTime);

		Map<String, Object> requestMap = this.getRequestParaMap(inv.getController().getRequest());
		logMap.put("requestMap", requestMap);
		logMap.put("args", args);
		log.info(JsonKit.toJson(logMap));
		
		inv.invoke();
		
		Date endTime = new Date();
		Long runTime = endTime.getTime() - startTime.getTime();
		logMap.remove("startTime");
		logMap.remove("requestMap");
		logMap.remove("args");
		logMap.put("endTime", new Date());
		logMap.put("runTime", runTime);
		log.info(JsonKit.toJson(logMap));

	}

	private Map<String, Object> getRequestParaMap(HttpServletRequest request) {
		HashMap<String, Object> results = new HashMap<String, Object>();
		Map<String, String[]> queryParms = request.getParameterMap();
		for (String key : queryParms.keySet()) {
			for (String value : queryParms.get(key)) {
				results.put(key, value);
			}
		}
		return results;
	}

}
